package org.king.controller;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.king.MainApplication;
import org.king.entity.Activity;
import org.king.entity.vo.ActivityEntity;
import org.king.entity.vo.Comment;
import org.king.global.SessionContext;
import org.king.service.ActivityService;
import org.king.util.AlertUtil;
import org.king.util.StringUtil;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.ResourceBundle;

@Component
public class MainController implements Initializable {
    private final ActivityService activityService;
    // 通过构造函数注入（推荐）
    public MainController(ActivityService activityService) {
        this.activityService = activityService;
    }
    @FXML
    private TableView<ActivityEntity> tableActivity;
    @FXML
    private TableColumn<ActivityEntity, Integer> userId;
    @FXML
    private TableColumn<ActivityEntity, String> name;
    @FXML
    private TableColumn<ActivityEntity, LocalDateTime> beginTime;
    @FXML
    private TableColumn<ActivityEntity, LocalDateTime> endTime;
    @FXML
    private TableColumn<ActivityEntity, String> address;
    @FXML
    private TableColumn<ActivityEntity, Integer> builder;
    @FXML
    private Button btnAdd;//添加活动
    @FXML
    private Button btnDelete;//删除活动
    @FXML
    private Button btnModify;//修改活动
    @FXML
    private Button btnSearch;//搜索活动
    @FXML
    private Button btnDetail;//详细的活动
    @FXML
    private Button btnJoin;//参加活动
    @FXML
    private Button btnComment;//增加评价
    @FXML
    private Button btnLogout;//退出界面
    @FXML
    private Button btnMy;//我的活动界面
    @FXML
    private Button btnAll;//所有活动


    //可观察对象，进行数据绑定
    private ObservableList<ActivityEntity> activityList;
    //引入repository
    //引用窗体，修改等窗体
    private Stage newStage = null;
    @Override //初始化
    public void initialize(URL url, ResourceBundle resourceBundle) {
        //获得数据
        activityList = FXCollections.observableArrayList(activityService.getAllActivities());
        //绑定数据源
        userId.setCellValueFactory(new PropertyValueFactory<>("id"));
        name.setCellValueFactory(new PropertyValueFactory<>("name"));
        beginTime.setCellValueFactory(new PropertyValueFactory<>("beginTime"));//后面修改为标准的时间格式
        endTime.setCellValueFactory(new PropertyValueFactory<>("endTime"));//后面修改为标准时间格式
        address.setCellValueFactory(new PropertyValueFactory<>("address"));
        builder.setCellValueFactory(new PropertyValueFactory<>("creator"));
        tableActivity.setItems(activityList);
        int currentUserId = SessionContext.getInstance().getCurrentUser().getId();//当前登录用户的id

        btnAdd.setOnAction(event -> {
            addOrModifyActivity(true);
        });
        btnModify.setOnAction(event -> {
            var selectIndex = tableActivity.getSelectionModel().getSelectedIndex();
            if(selectIndex == -1){return;}
            addOrModifyActivity(false);
        });
        btnDelete.setOnAction(event -> { //删除活动
            var selectIndex = tableActivity.getSelectionModel().getSelectedIndex();
            if(selectIndex == -1){return;}
            var selectActivity = activityList.get(selectIndex);
            var activityId = selectActivity.getId();
            if(selectActivity.getCreator()==currentUserId){
                activityService.deleteActivity(activityId);
                activityList.remove(selectIndex);
            }else{
                AlertUtil.showAlert(Alert.AlertType.INFORMATION,"error","不是你发布的活动,不能删除","o.O");
            }
        });
        btnSearch.setOnAction(event -> {
            searchActivitiesByDate();
        });
        btnDetail.setOnAction(event -> {
            showActivityDetails();
        });
        btnJoin.setOnAction(event -> {
            var selectIndex = tableActivity.getSelectionModel().getSelectedIndex();
            if(selectIndex == -1){return;}
            var selectActivity = activityList.get(selectIndex);
            var activityId = selectActivity.getId();
            if(LocalDateTime.now().isAfter(selectActivity.getEndTime())){
                AlertUtil.showAlert(Alert.AlertType.ERROR,"error","活动已经结束了","去其他地方看看吧");
            }
            else if(activityService.getUserJoinActivity(activityId,currentUserId)!=0){
                AlertUtil.showAlert(Alert.AlertType.ERROR,"error","你已经报名活动了，请勿重复报名","看看其他活动吧");
            }
            else if(selectActivity.getCreator()==currentUserId){
                AlertUtil.showAlert(Alert.AlertType.INFORMATION,"error","你已经是发布者了，不需要参与","pig.img");
            }
            else{
                if(activityService.addUserJoinActivity(currentUserId,activityId)!=0){
                    AlertUtil.showAlert(Alert.AlertType.INFORMATION,"ok","你已经成功参与了","请在个人界面查看O.O");
                }else{
                    AlertUtil.showAlert(Alert.AlertType.ERROR,"error","404 not found","请重试");
                }
            }
        });
        btnComment.setOnAction(event -> {
            updateActivityComment();
        });
        btnLogout.setOnAction(event -> {
            SessionContext.getInstance().logout();
            MainApplication.changeView("/view/auth/login-view.fxml");
        });
        btnMy.setOnAction(event -> {
            updateActivityList(null,1);
        });
        btnAll.setOnAction(event -> {
            showAllActivities();
        });
    }
    /**
     * 调用发布或者修改活动的窗口
     * @param isAddNew 是否是新建或者更改
     */
    private void addOrModifyActivity(boolean isAddNew) {
        //加载布局文件
        var fxmlLoader = new FXMLLoader(
                MainApplication.class.getResource("/view/addOrModify-view.fxml"));
        try {
            AnchorPane root = fxmlLoader.load();
            //装载“新增（或修改）窗体”控制器
            var controller = (AddOrModifyController) fxmlLoader.getController();
            //将主控制器引用传给“新增（或修改）窗体”控制器
            controller.setMainController(this);

            if (isAddNew) {
                var activity = new ActivityEntity(); //新增，创建一个空白数据对象
                controller.setActivity(activity);
            } else {
                //修改，取出当前选中的行所对应的对象
                ActivityEntity activity = (ActivityEntity) tableActivity.getSelectionModel().getSelectedItem();
                if(activity.getCreator()!=SessionContext.getInstance().getCurrentUser().getId()){
                    AlertUtil.showAlert(Alert.AlertType.INFORMATION,"error","不是你发布的，你不能修改","o.O");
                    return;
                }
                if (activity == null) return;
                //克隆一份传给对话框窗体控制器
                controller.setActivity((ActivityEntity) activity.clone());
            }

            //显示对话框窗体
            var scene = new Scene(root);
            newStage = new Stage();
            if (isAddNew) {
                newStage.setTitle("新增记录");
            } else {
                newStage.setTitle("修改记录");
            }
            newStage.setScene(scene);
            newStage.initModality(Modality.APPLICATION_MODAL);
            newStage.showAndWait();

        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
    /**
     * 调用评价窗口
     */
    private void updateActivityComment(){
        var fxmlLoader = new FXMLLoader(
                MainApplication.class.getResource("/view/comment-view.fxml")
        );
        try {
            AnchorPane root = fxmlLoader.load();
            //装载控制器
            var controller = (CommentController) fxmlLoader.getController();
            //将主控制器引用传给“新增（或修改）窗体”控制器
            controller.setMainController(this);

            ActivityEntity activity = (ActivityEntity) tableActivity.getSelectionModel().getSelectedItem();
            if (activity == null) return;
            else if(LocalDateTime.now().isBefore(activity.getBeginTime())){
                AlertUtil.showAlert(Alert.AlertType.ERROR,"error","活动还没结束","等活动结束再评价吧");
                return;
            }
            else if(activityService.getUserJoinActivity(activity.getId(),SessionContext.getInstance().getCurrentUser().getId())==0){
                AlertUtil.showAlert(Alert.AlertType.ERROR,"error","你没有参加该活动，不能评价","看看其他的吧");
                return;
            }
            controller.setActivity((ActivityEntity) activity.clone());

            //显示对话框窗体
            var scene = new Scene(root);
            newStage = new Stage();
            newStage.setTitle("评论");
            newStage.setScene(scene);
            newStage.initModality(Modality.APPLICATION_MODAL);
            newStage.showAndWait();

        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }
    //主窗口控制器提供回调方法,更新评价分数

    /**
     * 回调函数，更新用户的评价分数
     * @param activity 活动实体，进行更新
     * @param score 评分
     */
    public void onUpdateJoinActivityScore(ActivityEntity activity, int score,String comment) {
        int currentUserId = SessionContext.getInstance().getCurrentUser().getId();
        if(!StringUtil.isEmpty(comment)){
            Comment comment1 = new Comment(0,currentUserId,activity.getId(), comment);
            activityService.insertComment(comment1);
        }
        if(activityService.updateUserJoinActivityScore(activity.getId(),currentUserId,score)!=0){
            AlertUtil.showAlert(Alert.AlertType.INFORMATION,"ok","您的评价我们已经收到了","请返回查看");
        }else{
            AlertUtil.showAlert(Alert.AlertType.ERROR,"error","提交失败了","请稍后重试");
        }
        if(newStage!=null){
            newStage.close();
        }
    }
    //主窗体控制器提供将被对话窗体口“回调”的方法
    public void onAddOrEditActivity(boolean isAddNew, ActivityEntity act) {
        int currentUserId = SessionContext.getInstance().getCurrentUser().getId();
        Activity activity = new Activity(act.getId(), act.getName(), act.getDescription(),
                Timestamp.valueOf(act.getBeginTime()),
                Timestamp.valueOf(act.getEndTime()),
                act.getAddress(),
                act.getCreator());
        if(act.getEndTime().isBefore(act.getBeginTime())){
            AlertUtil.showAlert(Alert.AlertType.ERROR,"warning","警告","活动开始的时间必须早于结束时间");
        }
        if (isAddNew) {
            act.setCreator(currentUserId);
            activityService.addActivity(activity);
            act.setId(activity.getActivity_id());
            //将新对象加入到Activities集合中
            activityList.add(act);
        } else {
            var selectIndex = tableActivity.getSelectionModel().getSelectedIndex();
            if(selectIndex == -1){
                AlertUtil.showAlert(Alert.AlertType.ERROR,"warning","警告","请选中活动再进行更改");
                return;
            }
            if(activityService.updateActivity(activity)!=0) {//更新活动
                ActivityEntity currentActivity = tableActivity.getSelectionModel().getSelectedItem();
                //更新当前选中行所对应的数据对象
                currentActivity.setName(act.getName());
                currentActivity.setBeginTime(act.getBeginTime());
                currentActivity.setEndTime(act.getEndTime());
                currentActivity.setAddress(act.getAddress());
                currentActivity.setDescription(act.getDescription());
            }else{//更新失败了
                AlertUtil.showAlert(Alert.AlertType.ERROR,"error","更新失败","o.O");
            }
        }
        if (newStage != null) {
            newStage.close();
        }
    }
    //关闭窗口
    public void onCancelActivity() {
        newStage.close();
    }

    /**
     * 通过日期搜索活动，跳转到活动界面进行搜索
     */
    private void searchActivitiesByDate() {
        try {
            // 加载搜索界面
            FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("/view/search-view.fxml"));
            AnchorPane root = loader.load();

            // 获取控制器
            SearchController controller = loader.getController();
            controller.setMainController(this);

            // 创建新窗口
            Stage searchStage = new Stage();
            searchStage.setTitle("搜索活动");
            searchStage.setScene(new Scene(root));
            searchStage.initModality(Modality.APPLICATION_MODAL);
            searchStage.showAndWait();
        } catch (IOException e) {
            e.printStackTrace();
            AlertUtil.showAlert(Alert.AlertType.ERROR, "错误", "无法加载搜索界面", e.getMessage());
        }
    }
    /**
     * 根据日期，或者用户的id查找对应的活动
     * @param searchDate 日期
     * @param flag 一个判断，判断到底是哪个进行更新
     */
    public void updateActivityList(LocalDate searchDate, int flag) {
        try {
            if (searchDate == null && flag == 0) {
                AlertUtil.showAlert(Alert.AlertType.INFORMATION,"attention","请输入日期","没有查询到有用信息，请返回查询");
                return;
            }
            //查询用户的发布的活动
            else if (searchDate == null && flag == 1) {
                activityList.clear();
                activityList = activityService.getActivitiesByUserId(SessionContext.getInstance().getCurrentUser().getId());
            }
            else {
                // 否则按日期查询
                activityList.clear();
                activityList = activityService.getActivitiesByDate(searchDate);
            }

            if (activityList.isEmpty()) {
                AlertUtil.showAlert(Alert.AlertType.INFORMATION, "提示", "没有找到活动",
                        searchDate == null ? "系统中没有任何活动" :
                                "在 " + searchDate + " 没有找到任何活动");
            } else {
                tableActivity.setItems(activityList); // 更新表格数据
                tableActivity.refresh(); // 刷新表格显示
            }
        } catch (Exception e) {
            AlertUtil.showAlert(Alert.AlertType.ERROR, "错误", "查询失败",
                    "查询活动时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 列表展示所有的活动
     */
    private void showAllActivities() {
        try{
            activityList.clear();
            activityList = activityService.getAllActivities();
            tableActivity.setItems(activityList); // 更新表格数据
            tableActivity.refresh(); // 刷新表格显示
        }catch (Exception e){
            AlertUtil.showAlert(Alert.AlertType.ERROR,"error","查询失败","请联系管理员");
            e.printStackTrace();
        }
    }

    private void showActivityDetails() {
        try {
            // 加载详情界面
            FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("/view/detail-view.fxml"));
            AnchorPane root = loader.load();

            // 获取控制器
            DetailController controller = loader.getController();
            controller.setMainController(this);

            // 创建新窗口
            Stage detailStage = new Stage();
            detailStage.setTitle("活动详情");
            detailStage.setScene(new Scene(root));
            detailStage.initModality(Modality.APPLICATION_MODAL);
            detailStage.showAndWait();
        } catch (IOException e) {
            e.printStackTrace();
            AlertUtil.showAlert(Alert.AlertType.ERROR, "错误", "无法加载详情界面", e.getMessage());
        }
    }

    /**
     * 回调函数，用来显示活动的详情
     * @param activityId 活动id
     */
    // 提供给DetailController调用的方法，用于显示活动详情
    public void showActivityDetailsById(int activityId) {
        try {
            ActivityEntity activity = activityService.getActivity(activityId);

            int participantCount = activityService.getParticipantCount(activityId);
            double averageRating = activityService.getAverageRating(activityId);
            List<Comment> commentList = activityService.getCommentsByActivity(activityId);

            // 构建详情信息字符串
            final StringBuilder detailsBuilder = new StringBuilder(
                    "活动名称: " + activity.getName() + "\n" +
                            "开始时间: " + activity.getBeginTime() + "\n" +
                            "结束时间: " + activity.getEndTime() + "\n" +
                            "地点: " + activity.getAddress() + "\n" +
                            "描述: " + activity.getDescription() + "\n" +
                            "参加人数: " + participantCount + "\n" +
                            "平均评分: " + (averageRating > 0 ? String.format("%.1f", averageRating) : "暂无评分") + "\n"
            );

            if (!commentList.isEmpty()) {
                detailsBuilder.append("comments: { \n");
                commentList.forEach(comment -> {
                    detailsBuilder.append(comment.getText())
                            .append(" comment by ")
                            .append(comment.getUser_id())
                            .append("\n");
                });
                detailsBuilder.append("}");
            }

            final String details = detailsBuilder.toString();

            AlertUtil.showAlert(Alert.AlertType.INFORMATION, "活动详情", activity.getName(), details);
        } catch (Exception e) {
            AlertUtil.showAlert(Alert.AlertType.ERROR, "错误", "活动不存在",
                    "没有找到ID为" + activityId + "的活动");
        }
    }
}

